""" System imports """
import logging
from lxml import etree

""" Equinox """
from events import *
from sector import Sector

""" Constants """

""" Set up logging """
_log = logging.getLogger("equinox.map")

#----------------------------------------------------------------------  
class MapParseException(Exception):
        
    def __init__(self, value):
        self.value = value
        
    def __str__(self):
        return repr(self.value)
    

class Map:
    """..."""

    STATE_PREPARING = 0
    STATE_BUILT = 1


    #----------------------------------------------------------------------
    def __init__(self, evManager):
        self.evManager = evManager
        #self.evManager.RegisterListener( self )

        self.state = Map.STATE_PREPARING

        self.sectors = []
        
    #----------------------------------------------------------------------
    def load(self, file):
        _log.debug("Loading map: " + file)
        columnindex = 0
        rowindex = 0
        map = etree.parse(file)
        for row in map.iter("row"):
            self.sectors.append([])
            if row.tag == "row":
                for sector in row:
                    new_sector = Sector(self.evManager)
                    layer = sector.attrib.get("layer")
                    type = sector.attrib.get("type")
                    
                    if layer is None:
                        _log.error("layer not found on sector " + sector)
                        raise MapParseException("layer not found on sector " + sector)
                        break
                    elif type is None:
                        _log.error("type not found on sector " + sector)
                        raise MapParseException("type not found on sector " + sector)
                        break
                    else:
                        layer = int(layer)
                        new_sector.layer = layer
                        new_sector.type = type
                        new_sector.row = self.sectors[rowindex]
                        new_sector.coords = (columnindex, rowindex)
                        self.sectors[rowindex].insert(columnindex, new_sector)
                    columnindex = columnindex + 1
                    
                columnindex = 0
                rowindex = rowindex + 1
            else:
                _log.error("Row not found")
                raise MapParseException("Row not found")
            
        self.build()
            
    #----------------------------------------------------------------------
    def build(self):
        _log.debug("Building map")
        for row in self.sectors:
            for sector in row:
                self.getNeighbors(sector)

        self.state = Map.STATE_BUILT

        ev = MapBuiltEvent( self )
        self.evManager.post( ev )
    
    #----------------------------------------------------------------------    
    def getNeighbors(self, sector):
        if sector.neighbors == None:
            neighbors = range(4)
            if sector.coords[1] == 0:
                neighbors[DIRECTION_UP] = None
            else:
                neighbors[DIRECTION_UP] = self.sectors[sector.coords[1] - 1][sector.coords[0]]
            
            if sector.coords[1] == len(self.sectors) - 1:
                neighbors[DIRECTION_DOWN] = None
            else:
                neighbors[DIRECTION_DOWN] = self.sectors[sector.coords[1] + 1][sector.coords[0]]
    
            if sector.coords[0] == 0:
                neighbors[DIRECTION_LEFT] =  None
            else:
                neighbors[DIRECTION_LEFT] = self.sectors[sector.coords[1]][sector.coords[0] - 1]
    
            if sector.coords[0] == len(self.sectors[sector.coords[0]]) - 1:
                neighbors[DIRECTION_RIGHT] =  None
            else:
                neighbors[DIRECTION_RIGHT] = self.sectors[sector.coords[1]][sector.coords[0] + 1]
               
            sector.neighbors = neighbors
            return neighbors
        else:
            return sector.neighbors
    
    #----------------------------------------------------------------------  
    def notify(self, event):
        if isinstance(event, TickEvent):
            if self.state == self.STATE_PREPARING:
                pass
                #self.load("testmap.xml")
                